<?php
/**
 * Mailview
 * http://code.google.com/p/mailview/
 * Martin Tournoij <martin@arp242.net>
 * Mailview is free for any use, there are no restrictions.
 */

include('mailview2.php');
$mailview = new Mailview2();

if ((!isset($_GET['uid']) or $_GET['uid'] === '') and !isset($_POST['button']))
{
	header('Location: index.php');
	exit(0);
}

$link = Mailview\imap_open($_SESSION['config']);

# Display "raw" message as text
if (isset($_GET['rawmessage']))
{
	header('Content-Type: text/plain');
	print Mailview\imap_fetchheader($link, (int) $_GET['uid'], False);
	print Mailview\imap_body($link, (int) $_GET['uid'], False);
	exit(0);
}

# Display attachment
if (isset($_GET['attachment']))
{
	if (isset($_GET['view']))
		header(sprintf('filename="%s"', $_GET['name']));
	else
		header(sprintf('Content-Disposition: attachment; filename="%s"', $_GET['name']));

	$att = Mailview\imap_fetchbody($link, $_GET['uid'], $_GET['attachment']);

	header(sprintf('Content-Type: %s', $_GET['mime']));
	print Mailview\MailDecode($att, (int) $_GET['tenc']);

	exit(0);
}

### Button pressed
if (isset($_POST['button']))
{
	$_GET['uid'] = (int) $_POST['uid'];

	# Mark as read
	if ($_POST['button'] === 'read')
		Mailview\imap_setflag_full($link, (int) $_GET['uid'], '\Seen');
	# Mark for delete
	elseif ($_POST['button'] === 'delete')
	{
		Mailview\imap_setflag_full($link, (int) $_GET['uid'], '\Deleted');
		if (isset($_SESSION['config']['autoexpunge']))
			Mailview\imap_expunge($link);

		header('Location: index.php?mailbox=' . $_POST['mailbox']);
		exit(0);
	}
	# Mark as unread
	elseif ($_POST['button'] === 'unread')
		Mailview\imap_clearflag_full($link, (int) $_GET['uid'], '\Seen');
	# Mark as undelete
	elseif ($_POST['button'] === 'undelete')
		Mailview\imap_clearflag_full($link, (int) $_GET['uid'], '\Deleted');
	# Copy
	elseif ($_POST['button'] === 'Copy' and $_POST['newfolder'] != '')
		Mailview\imap_mail_copy($link, (int) $_GET['uid'], $_POST['newfolder']);
	# Move
	elseif ($_POST['button'] === 'Move' and $_POST['newfolder'] != '')
	{
		Mailview\imap_mail_move($link, (int) $_GET['uid'], $_POST['newfolder']);

		if (isset($_SESSION['config']['autoexpunge']))
			Mailview\imap_expunge($link);

		#header('Location: index.php?mailbox=' . $_GET['mailbox']);
		#exit(0);
	}
}

$vars = array(
	'header' => array(),
	'uid' => (int) $_GET['uid'],
	'body' => '',
	'attachments' => array(),
);

# Only show headers as defined in the config
$configheaders = explode(',', $_SESSION['config']['headers']);
$headers = Mailview\imap_fetchheader($link, (int) $_GET['uid']);
foreach ($configheaders as $field)
{
	foreach ($headers as $k => $v)
	{
		if (strtolower(ltrim($field, '*')) === strtolower($k))
		{
			if (is_array($v))
			{
				$p = $k . 'address';
				$v = $headers->$p;
			}

			$v = array(
				'text' => $v,
				'display' => array(),
			);
	
			if ($field[0] === '*')
				$v['display'][] = 'strong';

			$field = ltrim($field, '*');

			if (strtolower($field) === 'date')
				$v['text'] = date($_SESSION['config']['dateformat'], strtotime($v['text']));

			$vars['headers']["$field"] = $v;
			break;
		}
	}
}

# Loop over different parts
$struct = Mailview\imap_fetchstructure($link, (int) $_GET['uid']);

# Multipart
if ($struct->type === 1)
	$parts = Mailview\MailParts($struct);
else
{
	$parts = array('1' => $struct);
	$parts['1']->partno = 1;
}

foreach ($parts as $p)
{
	$isatt = False;

	# Text
	if ($p->type === 0 or $p->type === 2)
	{
		if ((isset($p->disposition) and $p->disposition === 'attachment') or strtolower($p->subtype) != 'plain' )
			$isatt = True;
	}
	# Multipart
	elseif ($p->type === 1)
	{
		# This should never happen
		continue;
	}
	# Message
	elseif ($p->type === 2)
		continue;
	# Application
	elseif ($p->type === 3)
		$isatt = True;
	# Audio
	elseif ($p->type === 4)
		$isatt = True;
	# Image
	elseif ($p->type === 5)
		$isatt = True;
	# Video
	elseif ($p->type === 6)
		$isatt = True;
	# Other
	elseif ($p->type === 7)
		$isatt = True;

	# Is attachment. Get more info.
	if ($isatt)
	{
		$att = array();
		$mime = Mailview\Mime($p);
		$att['view'] = $mime['1'];
		$mime = $mime['0'] . '/' . strtolower($p->subtype);
		$name = Mailview\SearchParameter($p, 'filename');
		if (empty($name))
			$name = Mailview\SearchParameter($p, 'name');
		if (empty($name))
			$name = "Untitled-$p->partno";

		$att['partno'] = $p->partno;
		$att['name'] = $name;
		$att['mime'] = $mime;
		$att['size'] = round($p->bytes / 1024, 1) . 'Kb';
		$att['encoding'] = $p->encoding;

		$vars['attachments'][] = $att;

		# iCalendar
		if ($att['mime'] === 'text/calendar')
		{
			$ical = Mailview\ParseiCal(Mailview\MailDecode(
				Mailview\imap_fetchbody($link, (int) $_GET['uid'], $p->partno, FT_PEEK), $p->encoding));

			$vars['body'] .= "<hr /><strong>Attached iCalendar:</strong><br />\n";
			foreach ($ical as $k => $v)
				$vars['body'] .= sprintf("<span class='label'>%s:</span>%s<br />\n", ucfirst($k), $v);
		}

	}
	else
		$vars['body'] .= Mailview\MailText($link, $p);
}

if ($_SESSION['config']['markasread'] === 'always')
	Mailview\imap_setflag_full($link, (int) $_GET['uid'], '\Seen');
else
	$vars['markasread'] = (int) $_SESSION['config']['markasread'] * 1000;


$mailview->Template($vars, $link);
?>
